<template>
  <div class="register">
    <el-form ref="loginRef" :model="loginInfo" :rules="rules">
      <el-form-item prop="identifier">
        <el-input v-model="loginInfo.identifier" placeholder="请输入用户名或邮箱" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginInfo.password" placeholder="请输入密码" type="password" />
      </el-form-item>
      <div class="login-control">
        <el-checkbox v-model="rememberAccount">记住账号</el-checkbox>
        <el-link type="primary">忘记密码</el-link>
      </div>
      <el-button type="primary" class="login-btn" @click="loginFn">登录</el-button>
    </el-form>
  </div>
</template>

<script>
import localCache from '@/utils/auth'
const rules = {
  identifier: [{ required: true, trigger: 'blur', message: '请输入用户名或邮箱' }],

  password: [{ required: true, trigger: 'blur', message: '请输入密码' }]
}
export default {
  data() {
    let password = ''
    let identifier = ''
    if (localCache.getCache(localCache.USER_INFO)) {
      password = localCache.getCache(localCache.USER_INFO).password
      identifier = localCache.getCache(localCache.USER_INFO).identifier
    }
    return {
      rememberAccount: true,
      loginInfo: {
        identifier,
        password
      },
      rules: rules
    }
  },

  methods: {
    async loginFn() {
      this.$refs.loginRef.validate(async (verify) => {
        if (verify) {
          //  验证通过。判断用户是否记住账号
          if (this.rememberAccount) {
            // 本地缓存
            localCache.setCache(localCache.USER_INFO, this.loginInfo)
          } else {
            localCache.removeCache(localCache.USER_INFO)
          }

          // 发送网络请求
          try {
            await this.$store.dispatch('user/login', this.loginInfo)
            this.$router.push('/')
          } catch (error) {
            this.$message.error('登录失败，请检查用户名或密码')
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.login-control {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 22px;
}
.login-btn {
  width: 100%;
}
</style>
